package com.lqk.netty.handler.chat;

import com.lqk.netty.handler.ServerHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author liqiankun@nnuo.com
 * @date 2023/3/31 13:57
 * @description
 **/
@Slf4j
public class ChatServerHeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        // 判断evt是否是IdleStateEvent（用于触发用户事件，包含 读空闲/写空闲/读写空闲 ）
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = "";
            if (event.state() == IdleState.READER_IDLE) {
                eventType = "进入读空闲...";
                log.info("进入读空闲...");
            } else if (event.state() == IdleState.WRITER_IDLE) {
                eventType = "进入读空闲...";
                log.info("进入写空闲...");
            } else if (event.state() == IdleState.ALL_IDLE) {
                eventType = "进入读写空闲...";
                log.info("channel关闭前，clients的数量为：{}", ServerHandler.clients.size());
                Channel channel = ctx.channel();
                // 关闭无用的channel，以防资源浪费
                channel.close();
                log.info("channel关闭后，clients的数量为：{}", ServerHandler.clients.size());
            }
            log.info(ctx.channel().remoteAddress() + "---超时事件---" + eventType);
        }
    }
}
